package com.kxq.zhuoyue.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kxq.zhuoyue.pageUtilEntity.Page;
import com.kxq.zhuoyue.po.Articles;
import com.kxq.zhuoyue.service.ArticlesService;
import com.kxq.zhuoyue.util.UUID;
import com.kxq.zhuoyue.util.result.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author xjh
 * @since 2023-09-01
 */
@Slf4j
@RestController
@RequestMapping("/article")
public class ArticlesController {

    @Autowired
    private ArticlesService articlesService;

    /**
     * 查询所有
     *
     * @param page
     * @return
     */
    @PostMapping("/getAll")
    public AjaxResult getAll(@RequestBody Page page) {
        Map map = new HashMap<>();
        LambdaQueryWrapper<Articles> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(Articles::getArticlesTitle,page.getArticlesTitle());
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<Articles> list = articlesService.list(queryWrapper);
        PageInfo pageInfo = new PageInfo<>(list);
        map.put("data", list);
        map.put("pageSize", pageInfo.getPageSize());
        map.put("total", pageInfo.getTotal());
        return AjaxResult.success("获取成功 !", map);
    }

    /**
     * 添加
     *
     * @param articles
     * @return
     */
    @PostMapping("/add")
    public AjaxResult add(@RequestBody Articles articles) {
        String id = UUID.getOrderIdByTime();
        articles.setArticlesId(id);
        articles.setArticlesStatus("未审核");
        boolean insert = articlesService.save(articles);
        if (insert) {
            return AjaxResult.success("添加成功 ！");
        } else {
            return AjaxResult.error("添加失败 ！");
        }
    }

    /**
     * 修改
     *
     * @param articles
     * @return
     */
    @PostMapping("/update")
    public AjaxResult update(@RequestBody Articles articles) {
        boolean update = articlesService.updateById(articles);
        if (update) {
            return AjaxResult.success("修改成功 ！");
        } else {
            return AjaxResult.error("修改失败 ！");
        }

    }

    /**
     * 删除
     * @param id
     * @return
     */
    @DeleteMapping("/delete/{id}")
    public AjaxResult delete(@PathVariable String id) {
        boolean b = articlesService.removeById(id);
        if (b) {
            return AjaxResult.success("删除成功 ！");
        } else {
            return AjaxResult.error("删除失败 ！");
        }

    }
}

